package com.exes;

import com.alibaba.fastjson2.JSON;
import com.db.CacheDb;
import com.microsoft.playwright.*;
import com.model.DocumentInfo;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.internal.StringUtil;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 获取知网搜索链接页面
 */
@Slf4j
public class CnkiSearchBuilder {
    private List<String> keywords = new ArrayList<>();

    private final String searchLinkEntryUrl = "https://kns.cnki.net/kns8/AdvSearch";

    public CnkiSearchBuilder(){
        this.keywords = Arrays.asList("计算机", "艺术");
    }

    public CnkiSearchBuilder(List<String> keywords){
        this.keywords = keywords;
    }

    private BrowserType.LaunchOptions options = new BrowserType.LaunchOptions();

    private AtomicInteger counter = new AtomicInteger(0);

    public void generate(String keyword, String startTime, String endTime, RequestBodyHandleCallback callback){
        options.setHeadless(false);
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(options);
            com.microsoft.playwright.Page page = browser.newPage();
            page.navigate(searchLinkEntryUrl);
            // 拦截请求
            page.route("**/GetGridTableHtml", route -> {
                int nowCounter = counter.incrementAndGet();
                Request request = route.request();
                route.resume();
                if(nowCounter > 1) {
                    callback.handle(request);
                }
            });
            page.setDefaultTimeout(15 * 1000);
            Locator inputTitleEle = page.locator("#gradetxt > dd:nth-child(2) > div.input-box > input[type=text]");
            inputTitleEle.fill(keyword, new Locator.FillOptions().setForce(true));
            page.evaluate("document.querySelector(\"#datebox0\").value = '" + startTime + "'");
            page.evaluate("document.querySelector(\"#datebox1\").value = '" + endTime + "'");
            Locator searchBtn = page.locator("body > div.search-box > div > div.search-classify > div > div.grade-search-content > div.search-mainbox.is-off > div.search-middle > div.search-buttons > input");
            searchBtn.click();
            Locator searchBtn2 = page.locator("body > div.search-box > div > div.search-classify > div > div.search-condition > input");
            page.waitForTimeout(3000);
            searchBtn2.click();
        }finally {

        }
    }

    Request resRequest = null;

    private void syncGetSearchSql(String keyword, String startTime, String endTime){
        resRequest = null;
//        options.setHeadless(false);
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(options);
            com.microsoft.playwright.Page page = browser.newPage();
            page.navigate(searchLinkEntryUrl);
            // 拦截请求
            page.route("**/GetGridTableHtml", route -> {
                int nowCounter = counter.incrementAndGet();
                Request request = route.request();
                route.resume();
                if(nowCounter > 1) {
                    resRequest = request;
                }
            });
            page.setDefaultTimeout(15 * 1000);
            Locator inputTitleEle = page.locator("#gradetxt > dd:nth-child(2) > div.input-box > input[type=text]");
            inputTitleEle.fill(keyword, new Locator.FillOptions().setForce(true));
            page.evaluate("document.querySelector(\"#datebox0\").value = '" + startTime + "'");
            page.evaluate("document.querySelector(\"#datebox1\").value = '" + endTime + "'");
            Locator searchBtn = page.locator("body > div.search-box > div > div.search-classify > div > div.grade-search-content > div.search-mainbox.is-off > div.search-middle > div.search-buttons > input");
            searchBtn.click();
            Locator searchBtn2 = page.locator("body > div.search-box > div > div.search-classify > div > div.search-condition > input");
            page.waitForTimeout(3000);
            searchBtn2.click();
        }finally {

        }
    }

    public Request getRequest(String keyword, String startTime, String endTime){
        syncGetSearchSql(keyword, startTime, endTime);
        while(resRequest == null){}
        return resRequest;
    }

    public Map<String, String> parseCnkiRequestData(Request request) throws UnsupportedEncodingException {
        String originData =  URLDecoder.decode(request.postData(), Charset.defaultCharset().displayName());
        String[] split = originData.split("&");
        Map<String, String> res = new HashMap<>();
        for (String s : split){
            String[] split1 = s.split("=");
            if(split1.length == 0){continue;}
            String key = split1[0];
            String value = split1.length > 1 ? split1[1] : "";
            res.put(key, value);
        }
        return res;
    }

    public static String getSearchSql(String keyWord, String startTime, String endTime){
        CnkiSearchBuilder cnkiSearchBuilder = new CnkiSearchBuilder();
        Request request = cnkiSearchBuilder.getRequest(keyWord, startTime, endTime);
        String res = "";
        try {
            Map<String, String> map = cnkiSearchBuilder.parseCnkiRequestData(request);
            res = map.get("SearchSql");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(StringUtils.isEmpty(res)) log.warn(new Date().toLocaleString() + ": " + " request search not found");
        return res;
    }

    public static void main(String[] args) {
        CnkiSearchBuilder cnkiSearchBuilder = new CnkiSearchBuilder();
//        cnkiSearchBuilder.generate("计算机", "2022-1-1", "2022-2-1", request->{
//            System.out.println(request.method());
//            System.out.println(request.url());
//            System.out.println(request.postData());
//            try {
//                System.out.println(URLDecoder.decode(request.postData(), Charset.defaultCharset().displayName()));
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//        });

//        Request request = cnkiSearchBuilder.getRequest("计算机", "2022-1-1", "2022-2-1");
//        System.out.println(request.method());
//        System.out.println(request.url());
//        System.out.println(request.postData());
//        try {
//            System.out.println(cnkiSearchBuilder.parseCnkiRequestData(request));
//            String s = JSON.toJSONString(cnkiSearchBuilder.parseCnkiRequestData(request));
//            System.out.println(s);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

        String searchSql = CnkiSearchBuilder.getSearchSql("计算机", "2022-1-1", "2022-2-1");
        System.out.println(searchSql);
    }

}
